package com.zkw.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;

/**
 * Created by Administrator on 2016/4/30 0030.
 * 客户端
 */
public class SocketChannelDemo {
    public static void startClient(){
        try {
            SocketChannel socketChannel = SocketChannel.open();
            socketChannel.connect(new InetSocketAddress("localhost",8999));
//            socketChannel.configureBlocking(false);
            //向服务端发送信息
            String request = "hello 老大!";
            ByteBuffer writeBuf = ByteBuffer.wrap(request.getBytes("UTF-8"));
            socketChannel.write(writeBuf);
            System.out.println("写入成功！");
            writeBuf.clear();

            //接收服务端返回的信息
            ByteBuffer readBuf = ByteBuffer.allocate(48);
            int size = socketChannel.read(readBuf);
            while (size>0){
                readBuf.flip();
                Charset charset = Charset.forName("UTF-8");
                System.out.println(charset.newDecoder().decode(readBuf));
                size = socketChannel.read(readBuf);
            }
            readBuf.clear();

            socketChannel.close();


        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    public static void main(String[] args) {
        startClient();
    }
}
